package com.qf.fmall2302.user.controller;

import cn.hutool.jwt.JWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.fmall2302.user.entity.Users;
import com.qf.fmall2302.user.service.IUsersService;
import com.qf.fmall2302.utils.FmallConstants;
import com.qf.fmall2302.vo.ResultVo;
import com.qf.fmall2302.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author dongjl
 * @since 2023-08-22
 */
@RestController
@RequestMapping("/user")
@Slf4j
@CrossOrigin
public class UsersController {

    @Autowired
    IUsersService usersService;

    @RequestMapping(value = "/login",method = {RequestMethod.GET,RequestMethod.POST})
    public ResultVo login(Users users) throws JsonProcessingException {
        log.info("入参为:users={}",users);

        // 使用shiro进行登录
        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(users.getUsername(), users.getPassword());

        subject.login(usernamePasswordToken);

//        Users principal = (Users) subject.getPrincipal();
        Object principal = subject.getPrincipal();

        // 当用户登录成功之后，创建 jwt
        // 把 principal ---》 json
        ObjectMapper objectMapper = new ObjectMapper(); // 获取springboot内置的json转换对象
        String userjson = objectMapper.writeValueAsString(principal);

        String jwt = JWT.create()
                .setSubject(userjson)
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 30))
                .setIssuedAt(new Date())
                .setKey("qfsyjava2302".getBytes())
                .sign();

        return ResultVo.ok(FmallConstants.SUCCESS_CODE, jwt, principal);

    }



    @PostMapping("/regist")
    public ResultVo regist(@RequestBody UserRegistVo userRegistVo) throws Exception {

        log.info("入参为:userRegistVo={}",userRegistVo);

        usersService.regist(userRegistVo);

        return ResultVo.ok(FmallConstants.SUCCESS_CODE,"ok",null);
    }

}
